package net.yla.smartbus.module.controller.pub.login;

import com.aliyuncs.utils.IOUtils;
import com.aliyuncs.utils.StringUtils;
import com.google.code.kaptcha.Producer;
import net.yla.smartbus.core.api.ApiResult;
import net.yla.smartbus.core.api.RequestCode;
import net.yla.smartbus.core.base.BaseController;
import net.yla.smartbus.core.constants.CacheKeyPrefix;
import net.yla.smartbus.core.exception.AppException;
import net.yla.smartbus.core.util.IPUtil;
import net.yla.smartbus.core.util.RedisUtil;
import net.yla.smartbus.core.util.Web;
import net.yla.smartbus.module.ba.right.admin.entity.CaptchasDO;
import net.yla.smartbus.module.ba.right.admin.service.CaptchasService;
import net.yla.smartbus.module.ba.right.login.dto.LoginDTO;
import net.yla.smartbus.module.ba.right.login.dto.UserSession;
import net.yla.smartbus.module.ba.right.login.form.LoginForm;
import net.yla.smartbus.module.ba.right.login.service.AdminLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static net.yla.smartbus.core.util.IPUtil.getIPAddr;
import static net.yla.smartbus.core.util.IPUtil.getUserAgent;

/**
 * @author KongXianDe
 * @date 2019/7/19 10:34
 */
@RestController
@RequestMapping("/api/web/admin")
public class AdminLoginController extends BaseController {

    @Autowired
    private AdminLoginService loginService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private Producer producer;
    @Autowired
    private CaptchasService captchasService;

    /**
     * 账号密码登录
     */
    @PostMapping("/login")
    public ApiResult passwordLogin( @RequestBody @Validated LoginForm form) {
        String ipAddr = getIPAddr(Web.getCurrentRequest());
        String userAgent = getUserAgent(Web.getCurrentRequest());
        String token = getToken();
        if (StringUtils.isNotEmpty(token)) {
            UserSession userSession = (UserSession) redisUtil.get(token);
            if (userSession != null) {
                LoginDTO loginDTO = new LoginDTO();
                // 续期不需要
                loginDTO.setToken(userSession.getToken());
                loginDTO.setState(userSession.getState());
                return success(loginDTO);
            }
        }

        return success(loginService.passwordLogin(form, ipAddr,userAgent));
    }

    /**
     * 账号注销
     *
     * @param form
     * @return
     */
    @PostMapping("/loginout")
    public ApiResult logout(@RequestBody @Validated LoginForm form) {
        String token = getToken();
        loginService.loginOut(token);
        return success();
    }

    /**
     * 登录token续期
     */
    @GetMapping("/renew")
    public ApiResult loginRenewal() {
        return success(loginService.loginRenewal(getToken()));
    }

    /**
     * 验证码
     */
    @PostMapping("/code/{time}")
    public void code(@PathVariable("time") String time, HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String code = producer.createText();
        logger.info("==================验证码:{}====================", code);
        String ipAddr = getIPAddr(Web.getCurrentRequest());
        CaptchasDO captchas = new CaptchasDO();
        long ip1 = IPUtil.ipv4ToLong(ipAddr);
        captchas.setCode(code);
        captchas.setIp(ip1);
        if (captchasService.insertSelective(captchas) < 1) {
            throw new AppException("获取验证码失败", RequestCode.Operate_Tip);
        }
        //生成图片验证码
        BufferedImage image = producer.createImage(code);
        //redis 60秒
        redisUtil.set(CacheKeyPrefix.NUMBER_CODE_KEY + ipAddr, code, 60L, TimeUnit.SECONDS);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
        } catch (IOException e) {
            logger.info("验证码响应异常");
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(out);
        }
    }


    @GetMapping("/getToken")
    public ApiResult testToken() {
        System.out.println("token:" + super.getToken());
        return success();
    }

    @GetMapping("/token")
    public ApiResult userInfo() {
        return success((UserSession) redisUtil.get(getToken()));
    }


    /**
     * 获取登录用户缓存信息
     */
    @GetMapping("/getUserSession")
    public ApiResult test() {
        //getUserSession().setLoginId("张三");
        System.out.println(getUserSession());
        return success(getUserSession().getLoginId());
    }

    /**
     * 判断后台服务是否正常，直接返回true
     */
    @GetMapping("/isNormal")
    public ApiResult isNormal() {
        return success(true);
    }

}
